package com.itheima.picture;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.awt.Color;

public class pictureTransfer {

    // 更丰富的ASCII字符集，从最暗到最亮
    private static final String[] ASCII_CHARS = {"$","@","B","%","8","&","W","M","#","*","o","a","h","k","b","d","p","q","w","m","Z","O","0","Q","L","C","J","U","Y","X","z","c","v","u","n","x","r","j","f","t","/","\\","|","(",")","1","{","}","[","]","?","-","_","+","~","<",">","i","!","l","I",";",":",",","/","^","`","'","."};

    // 缩放参数常量
    private static final double SCALE_FACTOR = 0.6;
    private static final double HEIGHT_ADJUSTMENT = 0.4;
    private static final String INPUT_PATH = "C://picture/1.jpg";
    private static final String OUTPUT_PATH = "C://picture/output5.txt";
//不同比例照片的参数调试
//2.jpg 0.6 0.4
//3.png 0.6 0.8

    public static void main(String[] args) {
        BufferedImage image = null;

        try {
            // 输入输出文件路径
            File inputFile = new File(INPUT_PATH);
            File outputFile = new File(OUTPUT_PATH);

            // 检查文件是否存在且可读
            if (!inputFile.exists() || !inputFile.canRead()) {
                System.err.println("无法读取输入文件，请检查路径是否正确或文件权限！");
                return;
            }

            // 创建父目录（如果不存在）
            if (!outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            }

            // 读取图像文件
            image = ImageIO.read(inputFile);
            if (image == null) {
                System.err.println("无法读取图像文件，请检查路径是否正确！");
                return;
            }

            // 设置缩放比例，并调整高度以适配字符显示
            int scaledWidth = (int) (image.getWidth() * SCALE_FACTOR);
            int scaledHeight = (int) (image.getHeight() * SCALE_FACTOR * HEIGHT_ADJUSTMENT);

            // 创建一个StringBuilder来构建最终的ASCII艺术字符串
            StringBuilder asciiArt = new StringBuilder();

            // 遍历缩放后的图像区域
            for (int y = 0; y < scaledHeight; y++) {
                for (int x = 0; x < scaledWidth; x++) {
                    // 按比例映射到原图坐标
                    int srcX = x * image.getWidth() / scaledWidth;
                    int srcY = y * image.getHeight() / scaledHeight;

                    // 获取当前像素的颜色
                    Color color = new Color(image.getRGB(srcX, srcY));

                    // 使用加权平均法计算亮度（更接近人眼感知）
                    int brightness = (int) (0.299 * color.getRed() + 0.587 * color.getGreen() + 0.114 * color.getBlue());

                    // 增强对比度
                    brightness = enhanceContrast(brightness);


                    // 映射到ASCII字符数组中的索引
                    int index = Math.min(ASCII_CHARS.length - 1, brightness * ASCII_CHARS.length / 256);

                    // 添加对应的ASCII字符
                    asciiArt.append(ASCII_CHARS[index]);
                }
                // 每行结束后添加换行符
                asciiArt.append('\n');
            }

            // 打印调试信息
            System.out.println("字符画内容长度：" + asciiArt.length());

            // 将ASCII艺术写入输出文件
            try (FileWriter writer = new FileWriter(outputFile)) {
                writer.write(asciiArt.toString());
            }

            System.out.println("字符画已生成并保存至：" + outputFile.getAbsolutePath());

        } catch (IOException e) {
            System.err.println("发生IO错误：" + e.getMessage());
            e.printStackTrace();
        } finally {
            // 如果有需要释放的资源，在这里进行
            // 对于BufferedImage，通常不需要显式释放，除非使用了特殊资源
        }
    }
    // 增强对比度
    private static int enhanceContrast(int brightness) {
        // 使用 S 曲线增强对比度
        double adjustedBrightness = (brightness / 255.0 - 0.5) * 1.5; // 调整范围为 [-0.75, 0.75]
        adjustedBrightness = Math.tanh(adjustedBrightness) * 0.5 + 0.5; // 使用 tanh 函数进行 S 曲线变换
        return (int) (adjustedBrightness * 255);
    }
}
